//
//  LBMediaPresentViewController.m
//  LangBa
//
//  Created by Mac on 2017/12/21.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "SMAddressChosedViewController.h"
@interface SMAddressChosedViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong) STButton                     *clearButton;
@property(nonatomic, strong) UIView                     *customView;
@property(nonatomic, strong) STButton                     *choseButton;/**< 请选择 */
@property(nonatomic, strong) NSMutableArray                     *chosedDicArray;/**< 选中的字典 */
@property(nonatomic, strong) UITableView                     *tableView;/**< <##> */
@property(nonatomic, strong) NSMutableArray                     *currentDataSouce;/**< <##> */
@property(nonatomic, strong) NSMutableArray<STButton*>                     *buttonArray;/**< <##> */
/*
 "name": "市辖区",
 "open": 0,
 "salesmanId": "0",
 "serialNo": "1201"
 */
@end

@implementation SMAddressChosedViewController

- (instancetype)init
{
    if (self == [super init]) {
        self.modalPresentationStyle = UIModalPresentationOverFullScreen;
    }
    return self;
}
#pragma mark --vc 生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    self.chosedDicArray = NSMutableArray.new;
    
    self.buttonArray = NSMutableArray.new;
    [self configSubView];
    [self sendListRequestWithId:@""];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self show];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    self.clearButton = [[STButton alloc] initWithFrame:STONEOBS_UI_UISCREEN_FRAME
                                                 title:nil
                                            titleColor:nil
                                             titleFont:0
                                          cornerRadius:0
                                       backgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.4]
                                       backgroundImage:nil
                                                 image:nil];
    [weakSelf.clearButton setClicAction:^(UIButton *sender) {
        [weakSelf dismiss];
    }];
    [self.view addSubview:_clearButton];
    
    self.customView = [[UIView alloc] initWithFrame:CGRectMake(0, UISCREEN_HEIGHT, UISCREEN_WIDTH, UISCREEN_HEIGHT / 2)];
    self.customView.centerX = UISCREEN_WIDTH / 2;
    self.customView.top = UISCREEN_HEIGHT;
    self.customView.backgroundColor = [UIColor whiteColor];
    self.customView.centerY = UISCREEN_HEIGHT / 2;
    [self.view addSubview:self.customView];
    
    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, 44, UISCREEN_WIDTH, 1)];
    line.backgroundColor = STONEOBS_UI_LINE_COLOR;
    //    [self.customView addSubview:line];
    [self updateChosedButton];
    self.customView.top = UISCREEN_HEIGHT ;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 45, UISCREEN_WIDTH, self.customView.height - 45) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = UIColor.whiteColor;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.customView addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.choseButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 60, 44)
                                                 title:@"请选择"
                                            titleColor:STONEOBS_UI_THEME_BACKGROUNDCOLOR
                                             titleFont:15
                                          cornerRadius:0
                                       backgroundColor:nil
                                       backgroundImage:nil
                                                 image:nil];
    [self.customView addSubview:self.choseButton];
    self.choseButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
}
- (void)updateChosedButton{
    __weak typeof(self) weakSelf =  self;
    for (UIButton * but in self.buttonArray) {
        [but removeFromSuperview];
    }
    self.buttonArray = NSMutableArray.new;
    CGFloat left = 0;
    for (NSInteger i =0 ; i < self.chosedDicArray.count; i ++) {
        NSDictionary * dic = self.chosedDicArray[i];
        
        NSString * name = dic[@"name"];
        CGFloat witdh =  [name stoneobs_fun_st_widthWithheight:44 font:15];
        
        STButton * itemButton = [[STButton alloc] initWithFrame:CGRectMake(left, 0, witdh + 30, 44)
                                                          title:name
                                                     titleColor:STONEOBS_UI_FIRST_TEXT_COLOR
                                                      titleFont:15
                                                   cornerRadius:0
                                                backgroundColor:nil
                                                backgroundImage:nil
                                                          image:nil];
        itemButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [self.buttonArray addObject:itemButton];
        left = itemButton.right;
        [self.customView addSubview:itemButton];
        [itemButton setClicAction:^(UIButton *sender) {
            [weakSelf onSelctedChosedButton:sender];
        }];
        itemButton.tag = 10000 + i;
    }
    self.choseButton.left = left;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.currentDataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    NSDictionary * dic = self.currentDataSouce[indexPath.row];
    if ([dic.allKeys containsObject:@"name"]) {
        cell.textLabel.text = dic[@"name"];
        
    }
    cell.textLabel.textColor = WH_UICOLOR_FROM_RGBA(0x333333);
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    if (self.chosedDicArray.count < 4) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    return cell;
}
/*

 "id": 2, "name": "北京市", "parent_id": 1, "code": "110000"
 */
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * dic = self.currentDataSouce[indexPath.row];
    if ([self isZhiXiaShi]) {
        if (self.chosedDicArray.count == 1) {
            [self.chosedDicArray addObject:dic];
            NSMutableArray * codeArray = NSMutableArray.new;
            NSMutableArray * placeArray = NSMutableArray.new;
            for (NSDictionary * modelDic in self.chosedDicArray) {
                NSString * serialNo = [modelDic[@"id"] description];
                NSString * name = [modelDic[@"name"] description];
                [codeArray addObject:serialNo];
                [placeArray addObject:name];
            }
            NSString * first = [self.chosedDicArray.firstObject[@"id"] description];
            [codeArray insertObject:first atIndex:0];
            [self dismissWithHandle:^{
                if (self.onSlectedhandle) {
                    self.onSlectedhandle(codeArray, placeArray);
                }
            }];
             return;
        }
       
    }
    if (self.chosedDicArray.count == 2) {
        //回调
        [self.chosedDicArray addObject:dic];
        NSMutableArray * codeArray = NSMutableArray.new;
        NSMutableArray * placeArray = NSMutableArray.new;
        for (NSDictionary * modelDic in self.chosedDicArray) {
            NSString * serialNo = [modelDic[@"code"] description];
            NSString * name = [modelDic[@"name"] description];
            [codeArray addObject:serialNo];
            [placeArray addObject:name];
        }
        [self dismissWithHandle:^{
            if (self.onSlectedhandle) {
                self.onSlectedhandle(codeArray, placeArray);
            }
        }];
    }else{
        NSString * name = dic[@"name"];
        NSString * serialNo = [dic[@"id"] description];
        bool exist = NO;
        for (NSDictionary * extDic in self.chosedDicArray) {
            NSString * existname = extDic[@"name"];
            if ([name isEqualToString:existname]) {
                exist = YES;
            }
        }
        [self.chosedDicArray addObject:dic];
//        if (!exist) {
//            [self.chosedDicArray addObject:dic];
//        }
        [self updateChosedButton];
        [self sendListRequestWithId:serialNo];
    }
    
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --Private Method
- (void)show{
    [UIView animateWithDuration:0.6
                          delay:0
         usingSpringWithDamping:0.6
          initialSpringVelocity:0.7
                        options:UIViewAnimationOptionLayoutSubviews
                     animations:^{
                         self.customView.bottom = UISCREEN_HEIGHT;
                     } completion:^(BOOL finished) {
                         
                     }];
}
- (void)dismiss{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.25 animations:^{
        self.customView.top = UISCREEN_HEIGHT;
        self.clearButton.alpha = 0;
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}
- (void)dismissWithHandle:(void(^)())handle{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.25 animations:^{
        self.customView.top = UISCREEN_HEIGHT;
        self.clearButton.alpha = 0;
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:^{
            if (handle) {
                handle();
            }
        }];
    }];
}
#pragma mark --Action Method

- (void)onSelectedCancleButton{
    
    [self dismiss];
    
}
- (void)onSelectedWhiteView{
    [self.view endEditing:YES];
}
- (void)onSelctedChosedButton:(UIButton*)sender{
    NSInteger index = [self.buttonArray indexOfObject:sender];
    if (self.chosedDicArray.count > index) {
        self.chosedDicArray = [self.chosedDicArray subarrayWithRange:NSMakeRange(0, index)].mutableCopy;
    }
    
    NSDictionary * dic = self.chosedDicArray.lastObject;
    if (!dic) {
        [self sendListRequestWithId:@"0"];
    }else{
        NSString * serialNo = [dic[@"id"] description];
        [self sendListRequestWithId:serialNo];
    }
    [self updateChosedButton];
}
- (BOOL)isZhiXiaShi{
    NSString * name = [self.chosedDicArray.firstObject[@"name"] description];
//    if ([name containsString:@"北京"] ||
//        [name containsString:@"重庆"]||
//        [name containsString:@"上海"]||
//        [name containsString:@"天津"]) {
//        return  YES;
//    }
    return NO;
}
#pragma mark --NetWork Method
- (void)sendListRequestWithId:(NSString*)addID{
    NSMutableDictionary * paramDic = [NSMutableDictionary new];
    if (!addID.length) {
        addID = @"";
        
    }


    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    [stoneobs_net_param_dic setObject:addID forKey:@"id"];
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/user/getArea"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumGet
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        self.currentDataSouce = [responseObject valueForKey:@"data"];
        [self.tableView reloadData];
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:error.desc];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
}
@end







